package com.scalar.chiptrack.operations.packingslip.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.LabelValueBean;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.operations.packingslip.dao.NewPackingSlipDAO;
import com.scalar.chiptrack.operations.packingslip.forms.SearchPackingSlipForm;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.operations.process.dao.FinishedGoodsDAO;
import com.scalar.chiptrack.operations.process.FinishedGoods;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.SalesOrderDAO;
import com.scalar.chiptrack.users.User;


public final class SearchPackingSlipAction extends ChipTrackAction
{
	public ActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response ) throws Exception
	{
		HttpSession session = request.getSession();
		User user 			= (User) session.getAttribute ( SessionKeys.USER_KEY );
		HashMap errors 		= new HashMap();
		HashMap info 		= new HashMap();
		String action 		= request.getParameter( "action" );
		if ( user == null )
		{
			session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY, "/searchPackingSlip.do?" + request.getQueryString() );
			return ( mapping.findForward( "login" ) );
		}

		if ( action == null )
		{
			action = "";
		}

		if( request.getAttribute( SessionKeys.INFO_MESSAGES ) != null )
		{
			info.putAll( ( HashMap ) request.getAttribute( SessionKeys.INFO_MESSAGES ) );
		}

		if( request.getAttribute( SessionKeys.ERROR_MESSAGES ) != null )
		{
			errors.putAll( ( HashMap ) request.getAttribute( SessionKeys.ERROR_MESSAGES ) );
		}
		SearchPackingSlipForm searchForm = (SearchPackingSlipForm) form;
		if( "Search".equalsIgnoreCase( action ) )
		{
			// Fetch the list for the search creteria
			// ArrayList list = PackingSlipDAO.loadAllPackingSlipsForSearch( salesOrderNo, customerPo, customerId, status, addressID);
            searchForm.setLocation("null");
			ArrayList list = NewPackingSlipDAO.loadAllPackingSlipsForSearch( searchForm, null, null );

			if ( list != null && list.isEmpty() == false )
			{
				request.setAttribute( "searchList", list );
			}
			else
			{
                errors.put( ERROR_PACKING_SLIP_NOT_FOUND, null );

			}
		}

		request.setAttribute( SessionKeys.INFO_MESSAGES, info );
		request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
		request.setAttribute( "SalesOrderList", SalesOrderDAO.loadAllSalesOrderIdAndNumbers() );
		request.setAttribute( "customerList", CustomerDAO.getAllCustomerNames() );
        request.setAttribute( "locations", VendorDAO.getFinishedGoodsAddresses() );
		request.setAttribute( "yearList", getYearList() );
        request.setAttribute ( "salesOrdersList", SalesOrderDAO.loadAllSalesOrderIds(2, "PackingSlipSalesOrders" ));//2 for all sales orders both sample, regular
        request.setAttribute ( "posList", SalesOrderDAO.loadAllCustomerPOs(2, "PackingSlipSalesOrders"));

        request.setAttribute ( "productList", loadManufacturingProducts () );

		return ( mapping.findForward ( "success" ) );
	}

    private ArrayList getYearList()
    {
		int year = 2000;
		ArrayList yearList = new ArrayList();
		for ( int i = 0; i <= 15; i++)
		{
			yearList.add( new LabelValueBean( year+"", year+"" ) );
			year++;
		}
        return yearList;
    }

    /**
	 * @param errors
	 * @param request
	 */
	private void searchMessage( HashMap errors, HttpServletRequest request, SearchPackingSlipForm searchForm ) throws ScalarException
	{
		String salesOrderNo 	= searchForm.getSalesOrderNumber();
		String customerPo 		= searchForm.getCustomerPo();
		int customerId 			= searchForm.getCustomerId();
		String status 			= searchForm.getSePsStatus();
		int addressID	 		= searchForm.getAddressID();

		// Search wether there is any sales order for the sales order number
		HashMap coolStatusMap = NewPackingSlipDAO.getLineItemStatusBySalesOrderId( salesOrderNo );

		if ( coolStatusMap.isEmpty() == false )
		{
			String temp = "No Packing Slip for ";

			if( salesOrderNo != null && salesOrderNo.trim().length() > 0 )
			{
				temp = temp + "Sales Order# : "+salesOrderNo+", ";
			}
			else if( customerPo != null && customerPo.trim().length() > 0 )
			{
				temp = temp + "Customer PO : "+ customerPo+", ";
			}
			else if( customerId != -1 && customerId != 0 )
			{
				temp = temp + "Customer : "+ CustomerDAO.loadCustomerById( customerId ).getCustomerName()+", ";
			}
			else
			{
				temp = "No Packing Slip found";
			}

			if( status != null && !status.equals( "0" ) )
			{
				temp = temp + "Status : "+status;
			}
			if( temp.substring( temp.length()-2 ).equals( ", " ) )
			{
				temp = temp.substring( 0, temp.length()-2 );
			}
			errors.put( temp, null );
			request.setAttribute( "SALES_ORDER_NO_FOR_SALES_ORDER_LINK", salesOrderNo );
		}
		else
		{
			String temp = "No Packing Slip for ";
			if( salesOrderNo!=null && salesOrderNo.trim().length() > 0 )
			{
				temp = "No Sales order for Sales Order# : "+salesOrderNo;
			}
			else if( customerPo != null && customerPo.trim().length() > 0 )
			{
				temp = temp + "Customer PO : "+ customerPo+", ";
				if( status != null && !status.equals( "0" ) )
				{
					temp = temp + "Status : "+status;
				}
			}
			else if( customerId != -1 && customerId != 0 )
			{
				temp = temp + "Customer : "+ CustomerDAO.loadCustomerById( customerId ).getCustomerName()+", ";
				if( status != null && !status.equals( "0" ) )
				{
					temp = temp + "Status : "+status;
				}
			}
			else
			{
				temp = "No Packing Slip found";
				if( status != null && !status.equals( "0" ) )
				{
					temp = "No Packing Slip found for " + "Status : "+status;
				}
			}
			if( temp.substring( temp.length()-2 ).equals( ", " ) )
			{
				temp = temp.substring( 0, temp.length()-2 );
			}
			errors.put( temp, null );
		}
	}

    public static ArrayList loadManufacturingProducts () throws Exception
    {
        ArrayList parts = new ArrayList ();
        Iterator list = FinishedGoodsDAO.loadFinishedGoods ().iterator ();

        parts.add ( new org.apache.struts.util.LabelValueBean ( "All Products", "" ) );
        while ( list.hasNext () )
        {
            FinishedGoods product = ( FinishedGoods ) list.next ();
            //It is better to replace with product Id here, instead of again searching the database with marketingpart no for productid
            //But i am leaving the other code as it is because we need to change lot of the code in the salesDAO. ;)
            if( product.getProductId() == 0 )
            {
                parts.add ( new org.apache.struts.util.LabelValueBean ( product.getManufacturingPartNo (), "" ) );
            }
            else
            {
                parts.add ( new org.apache.struts.util.LabelValueBean ( product.getManufacturingPartNo (), product.getProductId()+"" ) );
            }
        }

        return parts;
    }

}